import CardStore from '..'
import { action, observable, toJS } from 'mobx';
import { getRowColCons, getInputEntry, cubeDataInput, getLayoutFieldAttr, cubeFieldAttr, getFieldAttrLinkPage } from '../../../apis/card'
import { message, Modal } from "antd";
import _ from "lodash";
import window from '../../../util';
import Formula from './Formula';
import jQuery from 'jquery';
import { WeaLocaleProvider } from "ecCom";
import { deal4ReplaceDatas } from '../../form';
import { addDay, } from '../../../util/dateUtil';
import { guid } from '../../../util/typeUtil';
import moment from 'moment';

const getLabel = WeaLocaleProvider.getLabel;

export default class CubeTrigger {
  card: CardStore;
  params: any = {};
  onChangeFuns: any = {};
  linkPageFuns: any = {};
  formulaAction: any;
  @observable needSumFields: string[] = [];
  @observable datas: any;
  constructor(card: CardStore) {
    this.card = card;
    window.CubeTrigger = this;
    this.formulaAction = new Formula(this.card, this);
  }
  refFields = {};//用于触发目标字段关联的字段属性
  @observable colCals; //用于暂存行列规则
  @observable rowCals;
  @observable inputEntryData; //字段联动配置
  @observable loading:boolean = false;

  @action
  init = (params: any, callBack?: Function) => {
    this.params = params;
    this.colCals = this.rowCals = '';
    return Promise.all([
      getRowColCons(params),
      getInputEntry(params),   //字段联动
      getLayoutFieldAttr(params),   //布局字段属性
      getFieldAttrLinkPage(params),   //属性联动
    ]).then(([
      RowColCons,
      InputEntry,
      LayoutFieldAttr,
      LinkPage
    ]) => {
      this.doRowColCons(RowColCons);
      this.formulaAction.execute();//公式触发
      this.formulaAction.doFormulaBindChange(); //给公式字段绑定onchange方法触发公式
      this.doInputEntry(InputEntry);
      callBack && callBack();
      this.doLayoutFieldAttr(LayoutFieldAttr);
      this.doFieldAttrLinkPage(LinkPage);
    });
  }

  @action
  executeWhenAddRow = (detail, rowKey) => {
    const detailTable = this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail);
    const row = detailTable && detailTable.has(rowKey) && detailTable.$(rowKey);
    this.formulaAction.execute();//增加一行触发公式
    this.card.doSelectItemChange(row);
    const { base: { type } } = this.card;
    row && row.map(field => {
      /**
       * 新增明细，触发字段为空，新建布局触发，显示布局和编辑布局不触发
       */
      if (type == "1" || type == "2") {
        field.onChange(field.getValue());
      } else {
        if (field.getValue()) {
          field.onChange(field.getValue());
        }
      }

      //触发明细字段关联的字段属性
      if (this.refFields[field.key]) {
        //应该只需要触发其中一个关联字段的字段属性就行了
        var f_field = this.refFields[field.key][0];
        if (field) {
          const _triggersT: any = {};
          const triggerRow = _.compact(this.getTrigger(this.refFields[field.key], f_field, true, rowKey));
          if (triggerRow && !_.isEmpty(triggerRow)) {
            _.set(_triggersT, f_field, this.getTrigger(this.refFields[field.key], f_field, true, rowKey));
          }
          this.cubeFieldAttr(_triggersT, rowKey);
        }
      }
    });
  }

  @action
  executeWhenCopyRow = (detail, rowKey, rowValues) => {
    const { base: { type }, cubeForm } = this.card;
    const detailTable = cubeForm.has(detail) && cubeForm.$(detail);
    const row = detailTable && detailTable.has(rowKey) && detailTable.$(rowKey);
    this.formulaAction.execute();//增加一行触发公式
    this.card.doSelectItemChange(row);
    row && row.map(field => {
      if (type == "1" || type == "2" || type == '0') {
        field.onChange(rowValues);
      } 
      //触发明细字段关联的字段属性
      if (this.refFields[field.key]) {
        //应该只需要触发其中一个关联字段的字段属性就行了
        var f_field = this.refFields[field.key][0];
        if (field) {
          const _triggersT: any = {};
          const triggerRow = _.compact(this.getTrigger(this.refFields[field.key], f_field, true, rowKey));
          if (triggerRow && !_.isEmpty(triggerRow)) {
            _.set(_triggersT, f_field, this.getTrigger(this.refFields[field.key], f_field, true, rowKey));
          }
          this.cubeFieldAttr(_triggersT, rowKey);
        }
      }
    });
  }

  @action
  executeWhenDelRow = (detail, rowKey) => {
    const detailTable = this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail);
    rowKey && rowKey.forEach(element => {
      const row = detailTable && detailTable.has(element) && detailTable.$(element);
      row && row.map(field => {
        /**
         * 删除明细，触发列字段规则合计赋值主表字段
         */
        field.onChange('');
      });
    });
  }

  delcommafy = (num) => {
    if ((num + "").trim() == "") {
      return "";
    }
    num = num.replace(/,/gi, '');
    return num;
  }

  @action
  doColCals = (toField: string, changeField: string) => {
    _.set(this.card.allFields, `${changeField}.needSum`, true);
    const { isdetail, detail } = this.card.getFieldProps(changeField);
    if (isdetail && this.card.cubeForm.has(detail)) {
      let sum = 0;
      this.card.cubeForm.$(detail).map(row => {
        if (row.has(changeField)) {
          const { fieldtype } = this.card.getFieldProps(changeField);
          let fieldValue = row.$(changeField).getValue()
          if (fieldtype == 5) {
            // 千分位处理
            fieldValue = this.delcommafy(row.$(changeField).getValue());
          }
          let value = parseFloat(fieldValue);
          if (isNaN(value)) {
            value = 0;
          }
          sum += value;
        }
      });
      if (this.card.cubeForm.has(toField)) {
        this.card.cubeForm.$(toField).onChange(`${sum}`);
      }
    }
  }

  @action
  doRowCals = (rowCal: any, changeField: string, index?: string) => {
    const { cals, tofield } = rowCal;
    if (cals && tofield) {
      const { isdetail, detail } = this.card.getFieldProps(changeField);
      if (isdetail) {
        this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail).map(row => {
          if (!_.isUndefined(index) && row.key != index) {
            return;
          }
          if (row.has(changeField) && row.has(tofield)) {
            const _cals = cals.replace(/field[0-9]*/g, (fieldname: string) => {
              if (row.has(fieldname)) {
                let vals = row.$(fieldname).getValue() + "";
                while (vals.indexOf(",") > -1) {
                  vals = vals.replace(",", "");
                }
                let value = parseFloat(vals);
                if (isNaN(value)) {
                  value = 0;
                }
                return ` ${value}`;
              } else {
                return 0;
              }
            });
            try {
              const calValue = eval(_cals)
              row.$(tofield).onChange(`${calValue}`);
            } catch (e) {
              message.error(getLabel('383716', "行规则计算错误。"));
            }
          }
        });
      }
    }
  }

  @action
  doRowColCons = ({ status, errorCode, error, colCals, rowCals }: any, isInit = true) => {
    if (status != '1') {
      message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
      return;
    }
    if (colCals) {
      this.colCals = colCals;
      const needSumFields: string[] = [];
      _.each(colCals, (toField: string, changeField: string) => {
        this.doColCals(toField, changeField); //初始化执行一次
        if (isInit) {
          needSumFields.push(changeField);
          this.addOnChange(changeField, () => {
            this.doColCals(toField, changeField);
          })
          this.needSumFields = needSumFields;
        }
      });
    }
    if (rowCals) {
      this.rowCals = rowCals;
      _.each(rowCals, (rowCal: any, changeField: string) => {
        changeField = changeField.split('_')[0];
        if (rowCal) {
          this.doRowCals(rowCal, changeField);
          if (isInit) {
            this.addOnChange(changeField, (index?: string) => {
              this.doRowCals(rowCal, changeField, index);
            });
          }
        }
      });
    }
  }
  /*****外部调用一次行列计算 */
  doRowColConsComputed = () => {
    this.doRowColCons({ status: 1, colCals: this.colCals, rowCals: this.rowCals }, false);
  }


  @action
  findSameRowChilds = (fieldname) => {
    let newChangeFieldIds: any = [];  //filedid存储
    const parent = jQuery(`[id*=${fieldname}]`).parents("tr")[0];//被隐藏的行
    if (parent) {
      const childrenFields = jQuery(parent).find("*.fieldValue");//隐藏行内的field元素
      if (childrenFields) {
        Array.prototype.forEach.call(childrenFields, element => {   //获取fieldid
          const dataset = this.getDataset(element)
          newChangeFieldIds.push(dataset.fieldmark);
        });
      }
    }
    return newChangeFieldIds;
  }

  @action
  getDataset = (ele) => {
    if (ele.dataset) {
      return ele.dataset;
    } else {
      var attrs = ele.attributes,//元素的属性集合
        dataset = {}, name, matchStr;
      for (var i = 0; i < attrs.length; i++) { //是否是data- 开头
        matchStr = attrs[i].name.match(/^data-(.+)/);
        if (matchStr) { //data-auto-play 转成驼峰写法 autoPlay
          name = matchStr[1].replace(/-([\da-z])/gi, function (all, letter) {
            return letter.toUpperCase();
          });
          dataset[name] = attrs[i].value;
        }
      }
      return dataset;
    }
  }

  @action
  isdoByfield = (linkPage,selectFieldId1,value) => {
    let isdo = false;
    for(let i=0;i<linkPage.length;i++){
      let flag = false;
      const { selectFieldId,relationtype,selectFieldValue } = linkPage[i];
      if(selectFieldId == selectFieldId1){
        if((relationtype == "0"|| relationtype == "1")){//属于
          let selectvalues = selectFieldValue && selectFieldValue.split(",") || [];
          for(let i = 0;i<selectvalues.length;i++){
            if(selectvalues[i] == value){
              flag = true;
              break; 
            }
          }
          if((relationtype == "0" && flag == true) || (relationtype == "1" && flag == false)){
            isdo = true;
            break;
          }
        }else if(relationtype == "2" || relationtype == "3"){//包含、不包含
          let values = value && value.split(",") || [];
          for(let i = 0;i<values.length;i++){
            if(values[i] == selectFieldValue){
              flag = true;
              break; 
            }
          }
          if((relationtype == "2" && flag == true) || (relationtype == "3" && flag == false)){
            isdo = true;
            break;
          }
        }
      }
    };
    return isdo;
  }
  @action
  isDoFieldAttrLinkPage = ( selectvalue: string,relationtype : String ,value : String) =>{
    let flag = false;
    if(relationtype == "0" || relationtype == "1"){//属于、不属于
      let selectvalues = selectvalue && selectvalue.split(",") || [];
      for(let i = 0;i<selectvalues.length;i++){
        if(selectvalues[i] == value){
          flag = true;
          break; 
        }
      }
      if((relationtype == "0" && flag == true) || (relationtype == "1" && flag == false)){
        return true;
      }else{
        return false;
      }
    }else if(relationtype == "2" || relationtype == "3"){//包含、不包含
      let values = value && value.split(",") || [];
      for(let i = 0;i<values.length;i++){
        if(values[i] == selectvalue){
          flag = true;
          break; 
        }
      }
      if((relationtype == "2" && flag == true) || (relationtype == "3" && flag == false)){
        return true;
      }else{
        return false;
      }
    }
  }

  @action
  doFieldAttrLinkPage = ({ status, errorCode, error, linkPage }: any) => {
    if (status != '1') {
      message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
      return;
    }
    const addFunc = (fieldname: string, selectvalue: string,index:number, fun: Function) => {
      if(!_.get(this.linkPageFuns, `${fieldname}`)){
        _.set(this.linkPageFuns, `${fieldname}`,{})
      }
      const funs: Function[] = _.get(this.linkPageFuns, `${fieldname}.link${index}`) || [];
      funs.push(fun);
      _.set(this.linkPageFuns, `${fieldname}.link${index}`, funs);
    };
    const doLinkPage = (data: any, form: any, index?: string) => {
      data.changeFieldIds && _.isArray(toJS(data.changeFieldIds)) && data.changeFieldIds.map(fieldname => {
        const { isdetail, detail } = this.card.getFieldProps(fieldname);
        if ((!_.isUndefined(index) && isdetail && form.path.startsWith(detail))) { //与触发字段同一明细表
          if (data.viewAttr !== "5") {  //隐藏行的功能暂时先不做
            form.has(fieldname) && form.$(fieldname).setViewAttrs(data.selectFieldId, data.viewAttr);
          }
        } else if (_.isUndefined(index)) { // 主表触发
          if (isdetail) {  // 变更字段为明细表， 所有明细行都变更
            form.has(detail) && form.$(detail).map(row => {
              row.has(fieldname) && row.$(fieldname).setViewAttrs(data.selectFieldId, data.viewAttr);
            });
          } else {
            if (data.viewAttr === "5") {
                this.findSameRowChilds(fieldname).forEach(name => {
                form.has(name) && form.$(name).setViewAttrs(data.selectFieldId, data.viewAttr);
              });
            } else {
              // this.datas = data;
              form.has(fieldname) && form.$(fieldname).setViewAttrs(data.selectFieldId, data.viewAttr);
            }
          }
        }
      });
    };
    if (linkPage && _.isArray(linkPage)) {
      _.each(linkPage, (data,index1) => {
        const { selectFieldId, selectFieldValue } = data;
        addFunc(selectFieldId, selectFieldValue,index1, (index?: string) => {
          const { isdetail, detail } = this.card.getFieldProps(selectFieldId);
          if (isdetail) { // 明细表触发字段
            this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail).map(row => {
              if (!_.isUndefined(index) && row.key != index) {
                return;
              }
              doLinkPage(data, row, row.key);
            });
          } else {
            doLinkPage(data, this.card.cubeForm);
          }
        })
      });
      const runLinkPage = (data: any,i:number, index?: string) => {
        const { selectFieldId ,selectFieldValue} = data;
        const { isdetail, detail } = this.card.getFieldProps(selectFieldId);
        if (isdetail) {
          this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail).map(row => {
            if (!_.isUndefined(index) && row.key != index) {
              return;
            }
            const value = row.has(selectFieldId) && row.$(selectFieldId).getValue();
            const funs: Function[] = _.get(this.linkPageFuns, `${data.selectFieldId}.link${i}`);
            /***只有相等的情况下，或者为空的情况下才执行 */
            // if(!funs){ //QC554703  针对这个qc重新处理的
            //   this.card.cubeForm.clearAllViewAttr(selectFieldId, [], row);
            // }
            //if(selectFieldValue != value ){return}
            //this.card.cubeForm.clearAllViewAttr(selectFieldId, [], row);
            //判断该字段设置的属性联动是不是都不执行，如果都不执行则把该字段属性联动出的属性都清空
            if(!this.isdoByfield(linkPage,selectFieldId,value)){
              this.card.cubeForm.clearAllViewAttr(selectFieldId, [], row);
              return
            };
            //判断是否属性联动
            let flag = this.isDoFieldAttrLinkPage(selectFieldValue,data.relationtype,value);
            if (funs && _.isArray(funs) && flag) {
              this.card.cubeForm.clearAllViewAttr(selectFieldId, [], row);
              funs.map(fun => {
                if (fun && _.isFunction(fun)) {
                  fun(row.key);
                }
              });
            }
          })
        } else {
          const value = this.card.cubeForm.has(selectFieldId) && this.card.cubeForm.$(selectFieldId).getValue();
          const funs: Function[] = _.get(this.linkPageFuns, `${data.selectFieldId}.link${i}`);
            /***只有相等的情况下，或者为空的情况下才执行 */
          // if(!funs){ //QC554703  针对这个qc重新处理的
          //   this.card.cubeForm.clearAllViewAttr(selectFieldId);
          // }
          //if(selectFieldValue != value ){return}
          //this.card.cubeForm.clearAllViewAttr(selectFieldId);
           //判断该字段设置的属性联动是不是都不执行，如果都不执行则把该字段属性联动出的属性都清空
          if(!this.isdoByfield(linkPage,selectFieldId,value)){
            this.card.cubeForm.clearAllViewAttr(selectFieldId);
            return
          };
          //判断是否属性联动
          let flag = this.isDoFieldAttrLinkPage(data.selectFieldValue,data.relationtype,value);
          if (funs && _.isArray(funs) && flag) {
            this.card.cubeForm.clearAllViewAttr(selectFieldId);
            funs.map(fun => {
              if (fun && _.isFunction(fun)) {
                fun();
              }
            });
          }
        }
        this.card.cubeForm.validate();
      }


      _.each(linkPage, (data: any,i) => {
        runLinkPage(data,i);
        this.addOnChange(data.selectFieldId, (index?: string) => {
          runLinkPage(data,i, index);
        });
      });
    }
  }

  @action
  cubeFieldAttrLinkPage = (data: any, funs: any, index?: string) => {
    const { selectFieldId } = data;
    const { isdetail, detail } = this.card.getFieldProps(selectFieldId);
    if (isdetail) {
      this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail).map(row => {
        if (!_.isUndefined(index) && row.key != index) {
          return;
        }
        if (row.has(selectFieldId)) {
          const func = _.get(funs, row.$(selectFieldId).getValue());
          if (func && _.isFunction(func)) {
            func(row.key);
          }
        }
      })
    }
  }
  doFieldDateGet = (v) => {
    try {
      let result: any = v.match(/\"(.*)\"/);
      let hasDateStr = ''
      if (result.length > 1) {
        hasDateStr = result[1].replace(/\s*/g, "")
      }
      let newDate = new Date();
      if (hasDateStr.length > 0 && moment(newDate).format('YYYY-MM-DD') == hasDateStr.substring(0, 10)) {
        const days: any = Number(hasDateStr.substring(10));
        result = addDay(newDate, days > 0 ? days - 1 : days)
      }
      return result;
    } catch (error) { console.log(error) }
  }

  @action
  doLayoutFieldAttr = ({ status, errorCode, error, attrs, mapAttrs, valueAttrs, valuefrom, refFields }: any) => {
    if (status != '1') {
      message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
      return;
    }
    this.refFields = refFields;
    const tempParams = {};
    const { base: { type }, quickEditStore } = this.card;
    if (type == '0') {
      quickEditStore.recordParms(tempParams)
    }
    if (valueAttrs && !_.isEmpty(valueAttrs)) {
      _.each(valueAttrs, (v: string | any[], k: string) => {
        const { isdetail, detail } = this.card.getFieldProps(k);
        const isParm = valuefrom[k] || 'isOther';
        if (isdetail) {
          if (this.card.cubeForm.has(detail)) {
            tempParams[detail] = {};
            this.card.cubeForm.$(detail).map(row => {
              tempParams[detail][row.key] = {};
              if (isParm == 'isParm') {//是parm返回
                this.card.cubeForm.setValue(`${detail}.${row.key}.${k}`, v,true);
                tempParams[detail][row.key][k] = v;
              } else {
                let orivalue = this.card.cubeForm.getValue(`${detail}.${row.key}.${k}`);
                if (orivalue == '') {
                  this.card.cubeForm.setValue(`${detail}.${row.key}.${k}`, v,true);
                  tempParams[detail][row.key][k] = v;
                }
              }
            });
            if (typeof (v) == 'string' && v.indexOf('doFieldDate') > -1 && v.indexOf('$') < 0) {
              v = this.doFieldDateGet(v);
            }
          }
          //    this.card.cubeForm.$(detail).detailDefaultValue = { ...this.card.cubeForm.$(detail).detailDefaultValue, [k]:v };
          const _detailDefaultValue: any = {};
          if (v && _.isArray(v)) {
            _.set(_detailDefaultValue, k, deal4ReplaceDatas(v, this.card.getFieldProps(k).fieldtype))
          } else {
            _.set(_detailDefaultValue, k, v);
          }
          this.card.cubeForm.$(detail).detailDefaultValue = { ...this.card.cubeForm.$(detail).detailDefaultValue, ..._detailDefaultValue };
        } else {
          if (isParm == 'isParm') {//是parm返回
            this.card.cubeForm.setValue(k, v,true);
            tempParams[k] = v;
          } else {
            let orivalue = this.card.cubeForm.getValue(k);
            if (orivalue == '') {
              this.card.cubeForm.setValue(k, v,true);
              tempParams[k] = v;
            }
            //当前日期与数字的加减 --> 后端返回格式eg:doFieldDate("  2020-04-08  -5 ")
            if (typeof (v) == 'string' && v.indexOf('doFieldDate') > -1 && v.indexOf('$') < 0) {
              let value = this.doFieldDateGet(v);
              if (value != undefined) {
                this.card.cubeForm.setValue(k, value,true);
                tempParams[k] = v;
              }
            }

          }
        }
      });
    }
    /***
     * 显示布局针对parm参数记录暂存 
     * */
    if (type == '0' && !_.isEmpty(tempParams)) {
      quickEditStore.recordParms(tempParams)
    }
    if (mapAttrs && !_.isEmpty(mapAttrs)) {
      this.card.mapStore.mapAttrs = mapAttrs;
    }

    if (attrs && !_.isEmpty(attrs)) {
      const _triggers: any = {};
      _.each(attrs, (fields: string[], trigger: string) => {
        if (this.card.base.type == '1' || this.card.base.type == '0' || this.card.base.type == '2' || this.card.base.type == '4') {//0显示 1新建 2 编辑 4打印模板
          const triggerRow = _.compact(this.getTrigger(fields, trigger));
          if (triggerRow && !_.isEmpty(triggerRow)) {
            _.set(_triggers, trigger, triggerRow);
          }
        }
        this.addOnChange(trigger, (index?: string) => {
          const _triggersT: any = {};
          const triggerRow = _.compact(this.getTrigger(fields, trigger, true, index));
          if (triggerRow && !_.isEmpty(triggerRow)) {
            _.set(_triggersT, trigger, this.getTrigger(fields, trigger, true, index));
          }
          this.cubeFieldAttr(_triggersT);
        });
      })
      if (this.card.base.type == '1' || this.card.base.type == '0' || this.card.base.type == '2' || this.card.base.type == '4') {
        this.cubeFieldAttr(_triggers);
      }
    }
  }

  @action
  cubeFieldAttr = (_triggers: any, detailRowKey?) => {
    const newTriggers: any = {};
    _.forEach(_triggers, function (value, key) {
      newTriggers[key] = _.remove(value, function (n) {
        return n != null;
      });
    });
    if (!newTriggers || _.isEmpty(newTriggers)) {
      return;
    }
    cubeFieldAttr({ ...this.params, trigger: JSON.stringify(newTriggers) }).then(action(({ status, errorCode, error, datas }) => {
      if (status != '1') {
        message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
        return;
      }

      if (datas) {
        _.each(datas, (valueObjs: any, caltype: string) => {
          if (valueObjs && _.isArray(valueObjs)) {
            valueObjs.map((valueObj) => {
              const data = { ...valueObj };
              delete data.index;
              _.each(data, (value: string, fieldname: string) => {
                //if (_.isString(value)) {
                let _value;
                if (caltype == '1' || caltype == '3' || caltype == "0" || caltype == "4") {
                  _value = value;
                } else {
                  try {
                    _value = eval(value);
                  } catch (e) {
                    message.error(getLabel('383717', "字段属性计算错误"));
                    _value = '';
                  }
                }

                const { isdetail, detail } = this.card.getFieldProps(fieldname);
                if (isdetail) {
                  if (_.isUndefined(valueObj.index)) {
                    this.card.cubeForm.$(detail).values().forEach((item, index) => {
                      if (detailRowKey) {
                        if (detailRowKey == index) {
                          this.card.cubeForm.setValue(`${detail}.${index}.${fieldname}`, typeof _value == 'string' ? `${_value}` : _value,true);
                        }
                      } else {
                        this.card.cubeForm.setValue(`${detail}.${index}.${fieldname}`, typeof _value == 'string' ? `${_value}` : _value,true);
                      }
                    });
                  } else {
                    this.card.cubeForm.setValue(`${detail}.${valueObj.index}.${fieldname}`, typeof _value == 'string' ? `${_value}` : _value,true);
                  }
                } else {
                  this.card.cubeForm.setValue(fieldname, _value,true);
                }
                //  }
              });
            });
          }
        });
      }
    }));
  }


  inputEntryTriggers = [];

  @action
  doInputEntry = ({ status, errorCode, error, inputEntry, inputEntryConfig }: any) => {
    this.inputEntryData = { status, errorCode, error, inputEntry, inputEntryConfig };
    if (status != '1') {
      message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
      return;
    }
    const _triggers: any = {};
    _.each(inputEntry, (fields: string[], trigger: string) => {
      const { isdetail } = this.card.getFieldProps(trigger);
      if (this.card.base.type == '1' || isdetail && this.card.base.type == '2') {//编辑布局只有明细导入时候才主动触发字段联动
        const triggerRow = _.compact(this.getTrigger(fields, trigger));
        if (triggerRow.length > 0) {
          _.set(_triggers, trigger, triggerRow);
        }
      }
      this.addOnChange(trigger, (index) => {
        let isdel = '0';
        let isesb = '0';
        let pagefieldnames = new Array();
        inputEntryConfig.map((cfg) => {
          if (cfg.triggerfieldname == trigger) {
            isdel = cfg.isdel;
            isesb = cfg.isesb;
            pagefieldnames.push(cfg.pagefieldname);
          }
        });
        const _triggersT: any = {};
        _.set(_triggersT, trigger, _.compact(this.getTrigger(fields, trigger, true, index)));
        if (isdel == '1') {
          this.delNotSaveDetaildata(trigger, pagefieldnames);
        }
        this.cubeDataInput(_triggersT, isesb);
      });
    });
    if (this.card.base.type == '1' || this.card.base.type == '2' && this.card.detailImport && this.card.detailImport.uploadParams && this.card.detailImport.uploadParams.isImportDetail) {   //|| this.card.base.type == '2'  编辑布局一开始不触发字段联动
      if (this.card.params.isSaveCallback) { return; }
      this.cubeDataInput(_triggers);
    }

  }

  //删除未保存的明细表数据
  delNotSaveDetaildata = (trigger, pagefieldnames) => {
    let set = new Set();//要删除的明细表集合
    const that = this;
    pagefieldnames.map((pagefield) => {
      const { isdetail, detail } = that.card.getFieldProps(pagefield);
      if (isdetail) {
        set.add(detail);
      }
    });
    let delkeys = new Array();
    set.forEach(function (detail: any, sameElement, set) {
      if (that.card.cubeForm.has(detail)) {
        const detailTable = that.card.cubeForm.$(detail);
        let i = 0;
        detailTable.map((d) => {
          let row = detailTable.value[i];
          if (row.dtl_id == '' || row.dtl_id.length > 30) {
            delkeys.push(detail + "|" + d.key)
          }
          i++;
        });
      }
    });
    if (delkeys.length > 0) {
      Modal.confirm({
        content: getLabel('390243', '即将执行主表字段联动明细字段，要删除暂未保存的明细表联动数据吗？'),
        title: getLabel(131329, '信息确认'),
        onOk: () => {//删除未保存的明细表字段
          _.each(delkeys, key => {
            let info = key.split('|');
            const detailTable = that.card.cubeForm.$(info[0]);
            that.executeWhenDelRow(info[0], [info[1]]);
            detailTable.del(info[1]);
          });
        },
        onCancel: () => { }
      });
    } else {

    }
  }

  @action
  cubeDataInput = (_triggers: any, isesb?: String) => {
    let isTrue: boolean = false;  //联动清除的时候，主表联动明细表，明细表的数据就不要清除了吧；
    _.forEach(_triggers, (value, key) => {
      if (value[0]) {
        if (value[0]["index"] == undefined) {  //主表联动
          _.forEach(value[0], (v, k) => {
            if (!v) {
              isTrue = true;
            }
          })
        }
      }
    });
    if (isesb != '1' && !_triggers || _.isEmpty(_triggers)) {
      return;
    }
    let esbtrigger = {};
    if (isesb && isesb == '1') {
      esbtrigger = { esbtrigger: JSON.stringify(this.getSubmitData()) };
    }
    /***
     * 如果是显示布局，并且是明细表复制，不触发字段联动
     */
    const { base: { type },   cubeForm, getFieldEditState, quickEditStore } = this.card;
    if (type == '0' && quickEditStore.handletype == 'copy' ) {
      return 
    }
    this.loading = true
    cubeDataInput({ ...this.params, trigger: JSON.stringify(_triggers), ...esbtrigger }).then(action(({ status, errorCode, error, datas }) => {
      if (status == '1') {
        if (datas && _.isArray(datas)) {
          const quickEditDataInput: object = {};
          let mainFieldState = {};
          datas.map((d: any) => {
            let index = d.index;
            delete d.index;
            let tempObj = {};
            let tempDetail = '';
            //明细默认值已处理
            let detaildefault = false;
            _.each(d, (v: any, k: string) => {
              //   if(d[k]){
              const { isdetail, detail } = this.card.getFieldProps(k);
              if (isdetail && !isTrue) {
                if (cubeForm.has(detail)) {
                  tempDetail = detail;
                  const uuid = guid();
                  const detailTable = cubeForm.$(detail);
                  /**s
                   * 主表
                   *      1- 请求参数格式（trigger:{"field38255":[{"field38255":"B"}]}）
                   *      1- 返回格式：{"datas":[{"field38256":"文本BB"}],"status":"1"}
                   * 明细表
                   *      1- 请求参数格式（trigger:{"field38258":[{"index":0,"field38258":"B"}]}）
                   *      1- 返回格式：{"datas":[{"field38259":"文本BB","index":0}],"status":"1"}
                   *      1- 注意：明细表必须返回字段属性 index
                   */
                  if (_.isUndefined(index)) {
                    const fields = detailTable.map(f => parseInt(f.key));
                    const nextId = fields.length > 0 ? Math.max(...fields) + 1 : 0;
                    detailTable.add('', { key: `${nextId}` });
                    index = nextId;
                    if (type == '0') { //显示模板快速编辑下的字段联动
                      tempObj = { ...tempObj, dtl_id: uuid, dtl_index: index, ...d }
                      // quickEditDataInput[detail].push({ dtl_id: uuid, dtl_index: index, ...d });
                    }
                  } else {
                    if (type == '0') { //显示模板快速编辑下的字段联动
                      tempObj = { ...tempObj, dtl_id: detailTable.$(index).$('dtl_id').value || uuid, dtl_index: index, ...d }
                      // quickEditDataInput[detail].push({ dtl_index: index, ...d });
                    }
                  }
                  if (detailTable.has(index)) {
                    //处理明细表默认值
                    const field = cubeForm.$(detail);
                    let detailDefaultValue = toJS(field.detailDefaultValue) || {};
                    if(!detaildefault){
                      _.each(detailDefaultValue, (defaultValue: any, defaultField: string) => {
                        let value :any;
                        let flag = false;
                        if(defaultValue.value != undefined){
                          if(defaultValue.value){
                            flag = true;
                          }
                          value = defaultValue.valueObj
                        }else{
                          if(defaultValue){
                            flag = true;
                          }
                          value = defaultValue;
                        }
                        const row = detailTable.$(index);
                        if(row.has(defaultField) && flag){
                          cubeForm.setValue(`${detail}.${index}.${defaultField}`, value,true);
                        }
                      });
                    }
                    detaildefault = true;
                    const row = detailTable.$(index);
                    if (row.has(k)) {
                      cubeForm.setValue(`${detail}.${index}.${k}`, v,true);
                    }
                  }
                }
              } else {
                cubeForm.setValue(k, v,true);
                const { editstate } = getFieldEditState(k);
                if (editstate == '3') {
                  mainFieldState[k] = editstate;
                  cubeForm.$(k).setViewAttrs("", '2');
                }
              }
              //   }
            });
            if (tempDetail && !quickEditDataInput[tempDetail]) { quickEditDataInput[tempDetail] = [] };
            const tempobj1 = {};
            _.forEach(tempObj,(val:any,field)=>{
              if(_.isArray(val)){
                tempobj1[field] = {
                  value:val.map(d => d.id).join(','), 
                  valueSpan:val.map(d => d.name || d.lastname).join(','),
                  valueObj:val
                };
              }else{
                tempobj1[field] = val;
              }
            })
            tempDetail && quickEditDataInput[tempDetail].push(tempobj1);
          })
          /***
           * 1、快速编辑-新增后当前行可编辑
           * 2、更新数据到editstore
           */
          if (type == '0') {
            // console.log("quickEditDataInput",quickEditDataInput)
            cubeForm.updateValues(quickEditDataInput); //更新新增的
            const detailkeysState = {};
            _.forEach(quickEditDataInput, (detailValues: Array<Object>, detailname) => {
              const field = cubeForm.$(detailname);
              let detailkeys = _.keys(field.value[0]).filter(d => d.startsWith('field'));
              _.forEach(detailkeys, fieldid => {
                const { editstate } = getFieldEditState(fieldid);
                if (editstate == '3') {
                  detailkeysState[fieldid] = editstate;
                }
                for (let i = 0; i < detailValues.length; i++) {
                  field.$(detailValues[i]['dtl_index']).$(fieldid).setViewAttrs("", editstate == '2' ? '1' : (editstate == '3' ? '2' : '3'));
                }
              });
            })
            quickEditStore.update({ detailkeysState, detalCurrentValue: quickEditDataInput,mainFieldState });
            //快速编辑，字段联动后保存

            setTimeout(() => {
              if(!_.isEmpty(mainFieldState)){ //联动主表有必填，先校验主表
                // quickEditStore.editFieldKey = Object.keys(mainFieldState)[0];
                quickEditStore.checkRequireMain({}, true)
              }else{
                if(quickEditStore.handletype == 'copy'){
                  return ;
                }
                if (quickEditStore.handletype != 'add') {
                  quickEditStore.checkRequireDetail({}, true)
                }
              }
            }, 100)
          }
        }
      } else {
        message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
      }
      this.loading = false;
    }))
  }

  getTrigger = (fields: string[], trigger: string, nullTrigger?: boolean, index?: string) => {
    const { isdetail, detail } = this.card.getFieldProps(trigger);
    if (isdetail) {
      if (this.card.cubeForm.has(detail)) {
        const detailTable = this.card.cubeForm.$(detail);
        return detailTable.map(row => {
          if (!_.isUndefined(index) && row.key != index) {
            return null;
          }
          const tiggerValue = row.has(trigger) && row.$(trigger).getValue();
          if (!tiggerValue && !nullTrigger) {
            return null;
          }
          const _trigger: any = {
            index: row.key,
          };
          fields.map(f => {
            if (row.has(f)) {
              _.set(_trigger, f, row.$(f).getValue());
            } else if (this.card.cubeForm.has(f)) {
              _.set(_trigger, f, this.card.cubeForm.$(f).getValue());
            }
          })
          return _trigger;
        });
      }
    } else {
      const _trigger: any = {}
      const tiggerValue = this.card.cubeForm.has(trigger) && this.card.cubeForm.$(trigger).getValue();
      if (!tiggerValue && !nullTrigger) {
        return [null];
      }
      fields.map(f => {
        if (this.card.cubeForm.has(f)) {
          _.set(_trigger, f, this.card.cubeForm.$(f).getValue())
        }
      })
      return [_trigger];
    }
  }

  addOnChange = (field: string, onChange: Function) => {
    const f = _.get(this.onChangeFuns, field);
    if (f && _.isArray(f)) {
      _.set(this.onChangeFuns, field, [...f, onChange])
    } else {
      _.set(this.onChangeFuns, field, [onChange])
    }
  }


  getSubmitData = () => {
    const data: any = {};
    this.card.cubeForm.map(f => {
      if (f.key.startsWith('detail_')) {
        const detailExcel = this.card.modeExcel.getExcel(f.key);
        if (!detailExcel) {
          return;
        }
        const { detailProps } = detailExcel;
        let isHideNull = false;
        if (detailProps && detailProps.isHideNull) {
          isHideNull = true;
        }
        if (isHideNull) {
          f.map(row => {
            let isNull = true;
            row.map(d => {
              let value = d.getValue();
              if (d.key != 'checkbox' && !!value) {
                isNull = false;
              }
            });
            if (!isNull) {
              _.set(data, `${f.key}.[${row.key}]`, row.values())
            }
          });
        } else {
          _.set(data, f.key, f.values());
        }

        const submitdtlids = f.map(row => {
          return row.key;
        }).join(",");
        _.set(data, `submitdtlid${f.key.replace('detail_', '')}`, submitdtlids);
      } else {
        const { fieldhtmltype, fieldtype } = this.card.getFieldProps(f.path)
        if (fieldhtmltype == '3' && fieldtype == '17') {//多人力资源特殊处理
          const groupInfo = f.buildMultiUserGroupInfo(f.getValue(), f.valueObj);
          const groupnum = groupInfo.groupnum;
          for (let i = 0; i < groupnum; i++) {
            if (`group_${i}` in groupInfo)
              _.set(data, `${f.key}group${i}`, groupInfo[`group_${i}`]);
          }
          _.set(data, `${f.key}groupnum`, groupnum);
        }
        _.set(data, f.key, f.getValue());
      }
    });
    return data;
  }
}
